#include "manager.h"
using namespace std;

int UserManager::load_UserFromFile()
{
    string line;

    User tmpUser(0,"frist","000000","初始化用户");
    ifstream ifs(UserInfoFile, ios::in);

    if (!ifs.is_open())
    {
        ofstream ofs(UserInfoFile, ios::out);
        if (!ofs.is_open())
        {
            perror("ofs open failed");
            return -1;
        }

        this->userLib.push_back(std::make_shared<User>(tmpUser));
        ofs << tmpUser.serialize();
        ofs.close();
        return 0;
    }

    else
    {
        userLib.clear();
        while (getline(ifs, line))
        {
            tmpUser.deSerialize(line);
            this->userLib.push_back(make_shared<User>(tmpUser));
        }
        ifs.close();
        return 0; 
    }
}

int UserManager::save_UserToFile()
{
    ofstream ofs(UserInfoFile, ios::out);
    if (!ofs.is_open())
    {
        perror("ofs open failed");
        return -1;
    }

    for (vector<shared_ptr<User>>::iterator it = this->userLib.begin(); it != this->userLib.end(); ++it)
    {
        ofs<<(*(*it)).serialize();
    }
    return 0;
}

std::shared_ptr<User> UserManager::login_verification(const std::string& name, const std::string& password)
{
    auto it = find_if(this->userLib.begin(), this->userLib.end(),
        [&name, &password, this](shared_ptr<User> user) {return ((*user).getName() == name && (*user).getPassword() == password); });
    if (it == this->userLib.end())
        return nullptr;
    
    return (*it);
}

int UserManager::user_register(const std::string& name,const std::string& password)
{
    User tmpUser(0,name,password,"无");
    auto tmp = this->userLib.back();
    tmpUser.setId((*tmp).getId() + 1);

    auto it = find_if(this->userLib.begin(), this->userLib.end(),
        [&name, this](shared_ptr<User> user) {return (*user).getName() == name; });

    if ((*it) == nullptr)
    {
        this->userLib.push_back(make_shared<User>(tmpUser));
        return 0;
    }

    return -1;

}